package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Customer;
import cn.wolfcode.domain.CustomerTraceHistory;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.CustomerMapper;
import cn.wolfcode.mapper.CustomerTraceHistoryMapper;
import cn.wolfcode.qo.CustomerQueryObject;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.ICustomerService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CustomerServiceImpl implements ICustomerService {

    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private CustomerTraceHistoryMapper customerTraceHistoryMapper;

    @Override
    public void delete(Long id) {
       customerMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void insert(Customer customer) {
        Employee employee = (Employee)SecurityUtils.getSubject().getPrincipal();
        //设置状态
        customer.setStatus(Customer.STATUS_COMMON);
        //设置id
        customer.setSeller(employee);
        //设置录入员
        customer.setInputUser(employee);
        //设置录入时间
        customer.setInputTime(new Date());
       customerMapper.insert(customer);
    }

    @Override
    public Customer selectByPrimaryKey(Long id) {
        return customerMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Customer> selectAll() {
        return customerMapper.selectAll();
    }

    @Override
    public void update(Customer customer) {
        customerMapper.updateByPrimaryKey(customer);
    }

    @Override
    public PageInfo<Customer> query(CustomerQueryObject qo) {
        //判断当前用户的角色是什么,再赋值
        Subject subject = SecurityUtils.getSubject();
        if (!(subject.hasRole("admin") || subject.hasRole("Market_Manager"))){
            Employee employee = (Employee)subject.getPrincipal();
            qo.setSellerId(employee.getId());
        }
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(),"input_time desc");
        List<Customer> customers = customerMapper.queryForList(qo);
        return new PageInfo(customers);
    }

    @Override
    public void insert(CustomerTraceHistory customerTraceHistory) {
        //设置录入人
        customerTraceHistory.setInputUser((Employee) SecurityUtils.getSubject());
        customerTraceHistoryMapper.insert(customerTraceHistory);
    }

    @Override
    public void updateSellerId(Long customerId, Long sellerId) {
        customerMapper.updateSellerId(customerId,sellerId);
    }



}
